import { reactive, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue';
import page from './page.ts';
import { useRouter, useRoute } from 'vue-router';
export function useListComponent(props: any = {}) {
  const router = useRouter();
  const route = useRoute();
  const { proxy } = getCurrentInstance() as any;
  //页面信息
  const dataInfo: any = reactive({
    loading: false, //加载
    loadingMsg: '列表数据加载中', //加载
    pendingConfirmationOrder: 0, //待确认订单数
    table: {
      title: page.title, //表格-标题
      //表格-内容数据
      tbody: [],
      rowKey: '',
      theadCode: '', //basedatatable
      //表格-表头数据
      thead: [
        {
          label: '订单单号',
          prop: 'saleOrderGroupNumber',
          align: 'center',
          width: null,
        },
        {
          label: '产品名称',
          prop: 'productName',
          align: 'center',
          width: null,
        },
        {
          label: '协议书号',
          prop: 'xieYiShuHao',
          align: 'center',
          width: null,
        },
        {
          label: '客户名称',
          prop: 'customerName',
          align: 'center',
          width: null,
        },
        {
          label: '客户单号',
          prop: 'customerBillNo',
          align: 'center',
          width: null,
        },
        {
          label: '开单人员',
          prop: 'CreateOrderPerson',
          align: 'center',
          width: null,
        },
        {
          label: '产品编码',
          prop: 'productNumber',
          align: 'center',
          width: null,
        },
      ],
      //表格-搜索数据
      search: {
        pageIndex: 1, //当前页码
        pageSize: 30, //每页显示数据的数量
        totalCount: 0, //总数量
        queryDataBaseFiled: 'saleOrderGroupNumber', // 关键字查询字段，空值表示查询全部
        likeWords: '', // 查询关键字，空值表示查询全部
        beginTime: '', // 日期范围-开始时间
        endTime: '', // 日期范围-结束时间
        onlySelf: 0, // 是否只查自己创建的：0 查所有；1 只查自己
        isShowDisabled: -1, // 是否显示禁用：-1 所有；0 未作废；1 仅作废
        orderByFiled: '', // 排序字段
        orderByType: 0, // 排序方式：0 倒序；1 升序
        saleOrderGroupState: -1, // 订单状态：0待确认；1已确认；2作废；3撤单；4已完成；5即将到期；6已超期
        customerCode: '', // 客户编号
        ...props.query,
      },
      //表格-按钮数据
      btns: [
        {
          title: '导入标签订单',
          icon: 'Upload',
          type: '',
          click: (files: any, dataInfo: any) => {
            var formData = new FormData();
            formData.append('file', files.file);
            proxy.$api.OrderBusniess.AutoQuickOrderingByExcel(formData)
              .then((res: any) => {
                proxy.$message(`上传成功`);
                getTbody();
                dataInfo.loading = false;
              })
              .catch(() => {
                dataInfo.loading = false;
              });
          },
          accept: '.xlsx',
          download: {
            url: '标签订单.xlsx',
            name: `标签订单`,
          },
        },
        {
          title: '导出订单',
          icon: 'Download',
          type: '',
          click: () => {
            setLoading('导出数据,请稍等');
            proxy.$api.OrderBusniess.DownloadSaleOrderExportViewList2({
              ...dataInfo.table.search,
              saleOrderGroupState: -1,
              SaleOrderGroupStateList: [1, 4], //订单状态：0待确认；1已确认；2已作废；3已撤单；4已完成
            })
              .then((res: any) => {
                proxy.$downloadByBlob(res, '业务开单');
                dataInfo.loading = false;
              })
              .catch(() => {
                dataInfo.loading = false;
              });
          },
        },
        {
          title: '新建',
          icon: 'Plus',
          type: 'primary',
          click: () => {
            getPath({
              path: `${route.path}/details`,
              query: {
                type: 1,
              },
            });
          },
        },
      ],
      //表格-列表搜索
      operation: [
        {
          title: '复制信息',
          click: (row: any) => {
            let text = '';
            JSON.parse(JSON.stringify(row.saleOrderList))
              .filter((el: any) => el.isDisabled !== 1)
              .forEach((el: any, index: number) => {
                if (index !== 0) {
                  text += `\n\n`;
                }
                text += `${el.orderProduct.productName}`;
                text += `\n产品编号：${el.orderProduct.productNumber}`;
                text += `\n协议书号：${el.xieYiShuHao}`;
              });
            proxy.$copy(text, true);
          },
        },
        {
          title: (row: any) => {
            return [0].includes(row.saleOrderGroupState) && row.hasEditPower ? '编辑' : '查看';
          },
          click: (row: any) => {
            getPath({
              path: `${route.path}/details`,
              query: {
                type: [0].includes(row.saleOrderGroupState) && row.hasEditPower ? 2 : 3,
                saleOrderGroupCode: row.saleOrderGroupCode,
              },
            });
          },
        },
        {
          title: '作废',
          disabled: (row: any) => {
            return ![0].includes(row.saleOrderGroupState) || !row.hasEditPower;
          },
          click: (row: any, index: number) => {
            proxy.$messageInputBox('请填写作废原因', (value: string) => {
              getOrderState(row, 2, value);
            });
          },
        },
        {
          title: '撤回',
          disabled: (row: any) => {
            return ![1].includes(row.saleOrderGroupState) || !row.hasEditPower;
          },
          click: (row: any, index: number) => {
            proxy.$messageBox('是否撤回该单据，请确认！', () => {
              getOrderState(row, 0);
            });
          },
        },
        {
          title: '撤单',
          disabled: (row: any) => {
            return ![1].includes(row.saleOrderGroupState) || !row.hasEditPower;
          },
          click: (row: any, index: number) => {
            proxy.$messageInputBox('请填写撤单原因！', (value: string) => {
              getOrderState(row, 3, value);
            });
          },
        },
        {
          title: '完成发货',
          disabled: (row: any) => {
            return ![1].includes(row.saleOrderGroupState) || ![1].includes(row.deliverState) || !row.hasEditPower;
          },
          click: (row: any, index: number) => {
            proxy.$messageBox('是否完成发货，请确认！', () => {
              proxy.$api.OrderBusniess.UpdateSaleOrderDeliverState({
                saleOrderCode: row.saleOrderGroupCode, //分组订单编码
                deliverState: 2, //0-未发货、1-部分发货、2-已发货
              })
                .then((res: any) => {
                  proxy.$message(`发货成功`);
                  getTbody();
                })
                .catch(() => {});
            });
          },
        },
        {
          title: '结单',
          disabled: (row: any) => {
            return ![1].includes(row.saleOrderGroupState) || !row.hasEditPower;
          },
          click: (row: any, index: number) => {
            proxy.$messageBox('是否对该单据结单，请确认！', () => {
              getOrderState(row, 4);
            });
          },
        },
      ],
      searchThead: [
        {
          label: '订单单号',
          value: 'saleOrderGroupNumber',
        },
        {
          label: '产品名称',
          value: 'productName',
        },
        {
          label: '协议书号',
          value: 'xieYiShuHao',
        },
        {
          label: '客户名称',
          value: 'customerName',
        },
        {
          label: '客户单号',
          value: 'customerBillNo',
        },
        {
          label: '开单人员',
          value: 'CreateOrderPerson',
        },
        {
          label: '产品编码',
          value: 'productNumber',
        },
      ],
    },
  });
  const options = reactive({
    //单据状态
    orderState: [
      {
        label: '待确认',
        value: 0,
        type: 'info',
      },
      {
        label: '已确认',
        value: 1,
        type: '',
      },
      {
        label: '已作废',
        value: 2,
        type: 'warning',
      },
      {
        label: '已撤单',
        value: 3,
        type: 'warning',
      },
      {
        label: '已完成',
        value: 4,
        type: 'success',
      },
      {
        label: '即将到期',
        value: 5,
        type: 'danger',
      },
      {
        label: '已超期',
        value: 6,
        type: 'danger',
      },
    ],
    //数据状态
    dataBillState: [
      {
        label: '无数据',
        value: -1,
        type: 'info',
      },
      {
        label: '未到达',
        value: 0,
        type: 'info',
      },
      {
        label: '生产中',
        value: 1,
        type: '',
      },
      {
        label: '已完成',
        value: 3,
        type: 'success',
      },
    ],
    //缴库状态
    handInState: [
      {
        label: '待缴库',
        value: 0,
        type: 'info',
      },
      {
        label: '已缴库',
        value: 1,
        type: '',
      },
    ],
    //发货状态
    deliverState: [
      {
        label: '待发货',
        value: 0,
        type: 'info',
      },
      {
        label: '已发货',
        value: 1,
        type: '',
      },
    ],
    //生产状态
    productionState: [
      {
        label: '待生产',
        value: 0,
        type: 'info',
      },
      {
        label: '生产中',
        value: 1,
        type: '',
      },
      {
        label: '已完成',
        value: 2,
        type: 'success',
      },
    ],
    //客户信息
    customer: [],
    //客户折扣
    discountType: [
      {
        label: '无折扣',
        value: 0,
      },
      {
        label: '抹零',
        value: 1,
      },
      {
        label: '自定义',
        value: 4,
      },
    ],
  });
  // 更改单据状态
  const getOrderState = (row: any, state: number, reason?: string) => {
    const message: any = {
      0: '待确成功',
      1: '确认成功',
      2: '作废成功',
      3: '撤单成功',
      4: '结单成功',
    };
    proxy.$api.OrderBusniess.UpdateSaleOrderGroupState({
      saleOrderGroupCode: row.saleOrderGroupCode, //分组订单编码
      state: state, //订单状态：0待确认；1已确认；2作废；3撤单；4已完成；
      reason: reason, //作废原因/撤单原因
    })
      .then((res: any) => {
        proxy.$message(message[state] || '修改成功');
        getTbody();
      })
      .catch(() => {});
  };
  // 获取tabs数据
  const getPath = (obj: any, row?: any) => {
    const path = router.resolve(obj);
    // 在新窗口或标签页中打开目标路径
    const newWindow: any = window.open(path.href, '_blank');
    newWindow;
  };
  // 获取表数据
  const getTbody = () => {
    let _table: any = dataInfo.table;
    setLoading();
    proxy.$api.OrderBusniess.GetPageSaleOrderGroup({
      ..._table.search,
    })
      .then((res: any) => {
        _table.tbody = res.list;
        _table.search.totalCount = res.totalCount;
        dataInfo.loading = false;
        getPendingConfirmationOrder();
      })
      .catch(() => {
        dataInfo.loading = false;
      });
  };
  // 获取表数据
  const getPendingConfirmationOrder = () => {
    proxy.$api.OrderBusniess.GetPageSaleOrderGroup({
      pageIndex: 1, //当前页码
      pageSize: 999, //每页显示数据的数量
      totalCount: 0, //总数量
      queryDataBaseFiled: 'saleOrderGroupNumber', // 关键字查询字段，空值表示查询全部
      likeWords: '', // 查询关键字，空值表示查询全部
      beginTime: '', // 日期范围-开始时间
      endTime: '', // 日期范围-结束时间
      onlySelf: 0, // 是否只查自己创建的：0 查所有；1 只查自己
      isShowDisabled: -1, // 是否显示禁用：-1 所有；0 未作废；1 仅作废
      orderByFiled: '', // 排序字段
      orderByType: 0, // 排序方式：0 倒序；1 升序
      saleOrderGroupState: 0, // 订单状态：0待确认；1已确认；2作废；3撤单；4已完成；5即将到期；6已超期
      customerCode: '', // 客户编号
      ...props.query,
    })
      .then((res: any) => {
        dataInfo.pendingConfirmationOrder = res.totalCount;
      })
      .catch(() => {});
  };
  const setLoading = (title: string = '正在获取数据,请稍等...') => {
    if (!dataInfo.loading) {
      dataInfo.loading = true;
      dataInfo.loadingMsg = title;
    }
  };
  // 组件挂载后执行
  onMounted(() => {
    getTbody();
  });
  // 组件卸载前执行
  onBeforeUnmount(() => {});
  return { dataInfo, getTbody, options, getPath };
}
